package com.cc.flyingfish.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cc.flyingfish.entity.Danmu;
import com.cc.flyingfish.service.DanMuService;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CHENCHEN
 * @title
 * @createTime 2023-03-12 19:53
 */
@Slf4j
@Service
public class DanMuServiceImpl implements DanMuService {

    private static final String DANMU_KEY = "dm-video-";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void addDanMuToRedis(Danmu danmu) {
        String key = DANMU_KEY + danmu.getVideoId();
        String value = redisTemplate.opsForValue().get(key);
        List<Danmu> list = new ArrayList<>();
        if(!StringUtil.isNullOrEmpty(value)){
            list = JSONArray.parseArray(value, Danmu.class);
        }
        list.add(danmu);
        redisTemplate.opsForValue().set(key, JSONObject.toJSONString(list));
    }
}
